package flyrestaurant.jcy;

import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.net.ssl.HttpsURLConnection;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.params.HttpParams;

public class HttpUtils {
	public static final int TIMEOUT = 2000;
	
	public static Object post(String url,Map<String,String> params) throws Exception {
		HttpClient client = new DefaultHttpClient();
		HttpParams p = client.getParams();
		p.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, TIMEOUT);
		p.setParameter(CoreConnectionPNames.SO_TIMEOUT, TIMEOUT);
		HttpPost post = new HttpPost(url);
		if (params != null && !params.isEmpty()) {
			List<NameValuePair> formParams = new ArrayList<NameValuePair>();
			for (Map.Entry<String, String> e : params.entrySet())
				formParams.add(new BasicNameValuePair(e.getKey(),e.getValue()));
				UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(formParams,"UTF-8");
				post.setEntity(formEntity);
		}
		HttpResponse resp = client.execute(post);
		int status = resp.getStatusLine().getStatusCode();
		if (status != 200)
			throw new Exception("ErrorCode:"+status);
		HttpEntity entity = resp.getEntity();
		if (entity.getContentLength() == 0)
			return null;
		InputStream is = entity.getContent();
		ObjectInputStream ois = new ObjectInputStream(is);
		Object obj = ois.readObject();
		ois.close();
		is.close();
		client.getConnectionManager().shutdown();
		return obj;
	}
	
	public static void sendObject(String url,Object object) throws Exception {
		HttpsURLConnection conn = (HttpsURLConnection) new URL(url).openConnection();
		conn.setConnectTimeout(TIMEOUT);
		conn.setDoOutput(true);
		conn.setRequestMethod("POST");
		conn.setRequestProperty("Content-Type", "application/octet-stream");
		OutputStream os = conn.getOutputStream();
		ObjectOutputStream oos = new ObjectOutputStream(os);
		oos.writeObject(object);
		oos.flush();
		oos.close();
		os.close();
		conn.getInputStream().close();
		conn.disconnect();
	}
}
